/*
 * @Description: 粗略查询公交和站点页面（公交站点分别展示5条）
 * @Author: jun.fu
 * @Date: 2019-03-07 17:37:50
 * @Last Modified by:   jun.fu
 * @Last Modified time: 2019-03-07 17:37:50
 */
import React, { Component } from 'react'
import {
  StyleSheet,
  Text,
  View,
  FlatList,
  TouchableOpacity,
  Image
} from 'react-native'
import InputTitleBar from '../components/public/InputTitleBar'
import SearchItem from '../components/SearchCar/components/SearchItem'
import Notice from '../components/SearchCar/components/Notice'
import FoundNoData from '../components/SearchCar/components/FoundNoData'
import { px2dp } from 'rn-xiaobu-utils'
import { getImportDataRough } from '../components/SearchCar/api/api'
import XiaobuStorage from '../utils/XiaobuStorage';
import { searchData } from '../components/public/confs/StorageKeys';

export default class SearchCar extends Component {
  state = {
    list: [],
    busList: [],
    stationList: [],
    busCount: 0,
    stationCount: 0,
    searchText: '',
    errorShowTime: 0, // 错误展示剩余时间
    errorShowTimer: undefined, // 错误展示计时器
    foundNoData: false
  }

  cacheKey = searchData

  static navigationOptions = ({ navigation }) => {
    // 自定义输入框样式标题栏
    return {
      headerTitle: (
        <InputTitleBar
          back={navigation.getParam('back')}
          changeText={navigation.getParam('changeText')}
          defaultText={''}
        />
      )
    }
  }

  componentDidMount() {
    // 设置返回按钮函数，设置文字改变监听函数
    this.props.navigation.setParams({
      back: this.back,
      changeText: this.changeText
    })
    this.initHistoryList()
  }

  /**
   * 返回上一页
   */
  back = () => {
    console.log('is go back')
    this.props.navigation.dismiss()
  }

  /**
   * 输入框文字更改时，获取列表数据
   * @param text
   */
  changeText = text => {
    console.log('changeText:' + text)
    this.setState({ searchText: text })
    if (text) {
      // ajaxAsync('/bus/import', { IMPORT: text, PAGE_CAPACITY: 5 }).then(res => {
      //   if (this.state.searchText === text) {
      //     if ((!res.BUS_LIST || !res.BUS_LIST.length) && (!res.STATION_LIST || !res.STATION_LIST.length)) {
      //       this.cleanValue().then(() => {
      //         this.setState({
      //           foundNoData: true
      //         })
      //       })
      //       return
      //     }
      //     this.setState({
      //       busList: res.BUS_LIST || [],
      //       busCount: res.BUS_COUNT || 0,
      //       stationList: res.STATION_LIST || [],
      //       stationCount: res.STATION_COUNT || 0,
      //       foundNoData: false
      //     })
      //     let list = []
      //     if (res.BUS_LIST && res.BUS_LIST.length > 0) {
      //       list.push('busTitle')
      //       list = list.concat(res.BUS_LIST)
      //       if (res.BUS_COUNT && res.BUS_COUNT > 5) {
      //         list.push('busNeedMore')
      //       }
      //     }
      //     if (res.STATION_LIST && res.STATION_LIST.length > 0) {
      //       list.push('stationTitle')
      //       list = list.concat(res.STATION_LIST)
      //       if (res.STATION_COUNT && res.STATION_COUNT > 5) {
      //         list.push('stationNeedMore')
      //       }
      //     }
      //     console.log(list)
      //     this.setState({ list: list })
      //   }
      // }).catch(error => {
      //   console.log(error)
      //   this.setState({
      //     errorShowTime: 5000
      //   }, () => {
      //     this.errorShowTimer()
      //   })
      // })
      getImportDataRough(text)
        .then(res => {
          console.log(res)
          let list = []
          if (res.busList && res.busList.length > 0) {
            list.push('busTitle')
            list = list.concat(res.busList)
            if (res.busCount && res.busCount > 5) {
              list.push('busNeedMore')
            }
          }
          if (res.stationList && res.stationList.length > 0) {
            list.push('stationTitle')
            list = list.concat(res.stationList)
            if (res.stationCount && res.stationCount > 5) {
              list.push('stationNeedMore')
            }
          }
          console.log(list)
          this.setState({
            ...res,
            foundNoData: false,
            list: list
          })
        })
        .catch(error => {
          console.log(error)
          this.setState(
            {
              errorShowTime: 5000
            },
            () => {
              this.errorShowTimer()
            }
          )
        })
    } else {
      this.cleanValue().then(()=>{
        this.initHistoryList()
      })
    }
  }

  /**
   * 初始化搜索历史
   */
  initHistoryList = ()=>{
    let list = []
    XiaobuStorage.getItem(this.cacheKey).then(res=>{
      if (res) {
        list.push('historyTitle')
        list = list.concat(JSON.parse(res))
        list.push('historyClean')
        this.setState({
          list: list
        })
      }
    })
  }

  /**
   * 清空历史记录
   */
  cleanHistoryList = () => {
    XiaobuStorage.removeItem(this.cacheKey).then(()=>{
      this.setState({
        list: []
      })
    })
  }

  /**
   * 清空数据
   * @returns {Promise<any> | Promise<*>}
   */
  cleanValue = () => {
    return new Promise(resolve => {
      this.setState(
        {
          list: [],
          busList: [],
          busCount: 0,
          stationList: [],
          stationCount: 0,
          foundNoData: false
        },
        resolve
      )
    })
  }

  /**
   * 渲染搜索结果列表（没看到SectionList，自己做了头尾）
   * @param {{id,name,type,lat,lng}} item 要展示的信息
   * @returns {*}
   * @private
   */
  _renderItem = ({ item }) => {
    switch (item) {
      case 'busTitle': // 展示公交标题栏
        return <Text style={styles.title}>线路</Text>
        break
      case 'busNeedMore': // 展示公交需要更多按钮
        return (
          <TouchableOpacity
            onPress={() => this.seeMore(1)}
            style={styles.needMore}
            activeOpacity={0.6}
          >
            <Text>查看更多线路</Text>
          </TouchableOpacity>
        )
        break
      case 'stationTitle': // 展示线路标题栏
        return <Text style={styles.title}>车站</Text>
        break
      case 'stationNeedMore': // 展示线路公交按钮
        return (
          <TouchableOpacity
            onPress={() => this.seeMore(3)}
            style={styles.needMore}
            activeOpacity={0.6}
          >
            <Text>查看更多车站</Text>
          </TouchableOpacity>
        )
        break
      case 'historyTitle': // 展示线路标题栏
        return <Text style={styles.title}>搜索历史</Text>
        break
      case 'historyClean':
        return (
          <TouchableOpacity
            onPress={this.cleanHistoryList}
            style={[styles.needMore, { justifyContent: 'center', paddingLeft: 0 }]}
            activeOpacity={0.6}
          >
            <Text>清空历史搜索</Text>
          </TouchableOpacity>
        )
        break

      default:
        // 展示线路或站点
        if (item instanceof Object) {
          return (
            <SearchItem
              name={item.name}
              type={item.type}
              id={item.id}
              lat={item.lat}
              lng={item.lng}
              cacheKey={this.cacheKey}
            />
          )
        }
    }
  }

  /**
   * 查看更多
   * @param {Number} type 需要查看更多地类型(1，2、是线路；3、是站点)
   */
  seeMore = type => {
    // switch (type) {
    //   case 1:
    //     console.log('查看更多公交' + this.state.searchText)
    //     this.props.navigation.push('SearchDetails', {
    //       searchText: this.state.searchText,
    //       type: 1
    //     })
    //     break
    //   case 3:
    //     console.log('查看更多车站' + this.state.searchText)
    this.props.navigation.push('SearchDetails', {
      searchText: this.state.searchText,
      type: type,
      cacheKey: this.cacheKey,
      notShowCache: true
    })
    // break
    // }
  }

  /**
   * 协议错误提示展示时间计算
   */
  errorShowTimer = () => {
    // 错误时间计时器不存在时，新建计时器
    if (!this.state.errorShowTimer) {
      this.setState({
        errorShowTimer: setInterval(() => {
          // 时间超过规定时间，清空计时器
          if (this.state.errorShowTime - 1000 <= 0) {
            clearInterval(this.state.errorShowTimer)
            this.setState({
              errorShowTimer: undefined,
              errorShowTime: 0
            })
            return
          }
          this.setState({
            errorShowTime: this.state.errorShowTime - 1000
          })
        }, 1000)
      })
    }
  }

  render() {
    return (
      <View style={styles.container}>
        {this.state.errorShowTime > 0 ? (
          <Text style={styles.error}>网络开小差了</Text>
        ) : null}
        {this.state.list.length > 0 ? (
          <FlatList
            data={this.state.list}
            extraData={this.state}
            keyExtractor={(item, index) => index + ''}
            renderItem={this._renderItem}
            style={{ zIndex: 2 }}
          />
        ) : this.state.foundNoData ? (
          <FoundNoData />
        ) : (
          <Notice />
        )}
        <Image
          style={{
            width: '100%',
            height: px2dp(360),
            position: 'absolute',
            bottom: 0,
            zIndex: 1
          }}
          source={require('../../assets/img/background.png')}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F2F5F6'
  },

  title: {
    height: px2dp(74),
    backgroundColor: '#F2F5F6',
    color: '#999999',
    paddingLeft: px2dp(30),
    lineHeight: px2dp(74)
  },

  needMore: {
    height: px2dp(100),
    lineHeight: px2dp(100),
    backgroundColor: '#ffffff',
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: px2dp(46)
  },

  error: {
    backgroundColor: 'rgba(255, 153, 56, 1)',
    color: 'rgba(255, 255, 255, 1)',
    height: px2dp(60),
    lineHeight: px2dp(60),
    textAlign: 'center'
  }
})
